package com.huayi.gg.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;

import com.danikula.videocache.HttpProxyCacheServer;
import com.huayi.gg.MyApplication;
import com.huayi.gg.R;
import com.huayi.gg.broadcast.ReceiverMsg;
import com.huayi.gg.model.ServerBean;
import com.huayi.gg.ui.CustomVideoView;
import com.huayi.gg.ui.JZMediaIjk;
import com.huayi.gg.ui.JzvdStdShowTextureViewAfterAutoComplete;
import com.huayi.gg.utils.GlideImageLoader;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.jzvd.JZUtils;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

public class ImageActivity extends Activity {

    private ImageView imgshow;
    JzvdStdShowTextureViewAfterAutoComplete mVideoView;
    private Context mcontent;
    private String[] items;
    public int index=0;
    private Handler mHandler = new Handler();

    private  Timer mTimer;
    private static final int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_image);
        mcontent  =this;
        mVideoView=  findViewById(R.id.videoplayer);
        mVideoView.startButton.setVisibility(View.GONE);



        imgshow=  findViewById(R.id.imgshow);


        String imgurl = getIntent().getStringExtra("url");
        items = imgurl.split(",");
        List<String> result = new ArrayList<>();
        for (String s : items) {
            if (s.length() > 0) {
                result.add(s);
            }
        }
        items= result.toArray(new String[0]);
        initData();


        registerReceiver();
    }

    @SuppressLint("WrongConstant")
    public   void  initData(){

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
            } else {
                showData();
            }
        }
       SharedPreferences  sp = getSharedPreferences("cache", Context.MODE_PRIVATE);
        String code = sp.getString("code","");
        Toast.makeText(this,code,5000).show();

    }

    private  void  showData(){

        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // 切换到下一个视频



                        String url = items[index];
                        String type = url.substring(url.lastIndexOf(".") + 1);
                        if(type.toLowerCase().equals("mp4")){
                            imgshow.setVisibility(View.GONE);
                            mVideoView.setVisibility(View.VISIBLE);
                            mVideoView.setUrl(url);
                            mVideoView.setUp(MyApplication.getVideoCacheProxy(mcontent).getProxyUrl(url), "", 1,
                                    JZMediaIjk.class);
                            mVideoView.setVideoImageDisplayType(mVideoView.VIDEO_IMAGE_DISPLAY_TYPE_FILL_PARENT);
                            mVideoView.startVideo();


                        }else{
                            imgshow.setVisibility(View.VISIBLE);
                            mVideoView.setVisibility(View.GONE);
                            Glide.with(mcontent).load(url).into(imgshow);



                        }

                        index++;
                        if (index >= items.length) { // 播放完所有的视频，重新从第一个视频开始播放
                            index = 0;
                        }

                    }
                });
            }
        }, 0, 1000*15);






    }


    private void registerReceiver(){

        try {
            IntentFilter filter1 = new IntentFilter();
            filter1.addAction(ReceiverMsg.image);
            filter1.addAction(ReceiverMsg.close);
            filter1.addAction(ReceiverMsg.rotate);
            filter1.setPriority(Integer.MAX_VALUE);
            mcontent.registerReceiver(myReceiver1, filter1);

        } catch (Exception e) {

        }
    }
    private BroadcastReceiver myReceiver1 = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if(action.equals(ReceiverMsg.image)){


                    String imgurl = intent.getStringExtra("url");
                    items = imgurl.split(",");



                }else  if(action.equals(ReceiverMsg.close)){

                    finish();


                }else  if(action.equals(ReceiverMsg.rotate)){


                    ServerBean bean = (ServerBean) intent.getSerializableExtra("chatbean");

                    String content = bean.content;

                    if(content.equals("1")){
                        //横屏
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);


                    }else{
                        //竖屏
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }


                    Toast.makeText(mcontent,"设置成功",Toast.LENGTH_LONG).show();



                }

            } catch (Exception e) {

            }

        }

    };
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
            return false;
        }else if(keyCode==KeyEvent.KEYCODE_HOME){


            JzvdStd.releaseAllVideos();

            MyApplication application = (MyApplication) getApplication();
            application.stopSocket();


        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();


        try{
            if(myReceiver1!=null){
                unregisterReceiver(myReceiver1);
            }

            mTimer.cancel();

            Jzvd.releaseAllVideos();
        }catch (Exception ee){

        }



    }



}
